﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class secondBookList : System.Web.UI.Page
{
    /*
      *  产品列表  每页显示20个产品
      *  在产品展示界面，根据传进来的产品种类 动态显示内容
      *       小类产品
      *       热门产品
      *       最新产品   
      */
    String SmallType_Namestr;  // 获得传进来的SmallType_Namestr小类名称
    String where;              // 传进来的筛选条件
    int IsNewProduct;          // 标识新产品
    int IsHotProduct;          // 标识热门产品

    String selectStr;          // 筛选条件

    DAL.DataOperate.PageDivided pageDAL = new DAL.DataOperate.PageDivided();
    const int PageSize = 20;   // 定义每页显示记录
    int PageCount;             // 页面总数
    int RecCount;              // 记录集的总行数
    int CurrentPage;           // 当前页面
    int Pages;                 // 页数
    int JumpPage;              // 跳到第几页

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //--------------------------------------------------------------------------------------------------
            if (!object.Equals(Request.QueryString["SmallType_Namestr"], null))   // 如果是小类查询
            {
                SmallType_Namestr = Request.QueryString["SmallType_Namestr"];
                selectStr = " SmallType_Namestr like '%" + SmallType_Namestr + "%' ";
                selectStr += " and Book_Idint in (select Book_Idint from tbSecondBook_Seller) ";
            }
            else if (!object.Equals(Request.QueryString["IsNewProduct"], null))   // 如果最新产品
            {
                IsNewProduct = Int32.Parse(Request.QueryString["IsNewProduct"]);
                if (IsNewProduct == 1)
                {
                    selectStr = "";
                }
            }
            else if (!object.Equals(Request.QueryString["IsHotProduct"], null))  // 如果是热门产品
            {
                IsHotProduct = Int32.Parse(Request.QueryString["IsHotProduct"]);
                if (IsHotProduct == 1)
                {
                    selectStr = "";
                }
            }
            else if (!object.Equals(Application["where"], null)) // 根据条件筛选                                                                
            {
                // 获得筛选条件
                Application.Lock();
                where = Application["where"].ToString();
                String[] wherelist = new String[4];
                GetWhereInfor(where, wherelist);
                Application.UnLock();

                if (wherelist[2].ToString() == null || wherelist[2].ToString() == "")
                    wherelist[2] = float.MinValue.ToString();

                if (wherelist[3].ToString() == null || wherelist[3].ToString() == "")
                    wherelist[3] = float.MaxValue.ToString();

                selectStr = "  Book_Namestr like '%" + wherelist[0] + "%' ";
                selectStr += "  and SmallType_Namestr like '%" + wherelist[1] + "%' ";
                selectStr += "  and Book_Priceflo*Book_Discountflo BETWEEN " + wherelist[2] + " and " + wherelist[3];
                selectStr += " and Book_Idint in (select Book_Idint from tbSecondBook_Seller) ";
            }
            else
            {
                selectStr += " Book_Idint in (select Book_Idint from tbSecondBook_Seller) ";
            }
            //--------------------------------------------------------------------------------------------------
            if (!object.Equals(Session["SelectStr"], null))  // 设置筛选条件
            {
                Session.Remove("SelectStr");
            }
            Session["SelectStr"] = selectStr;
            SetPageInfor();
        }
    }
    // 设置页面信息（页数，当前页，总页数）
    public void SetPageInfor()
    {
        RecCount = Calc();                           // 通过Calc()函数获取总记录数
        PageCount = RecCount / PageSize + OverPage();// 计算总页数（加上OverPage()函数防止有余数造成显示数据不完整）

        ViewState["PageCounts"] = RecCount / PageSize - ModPage();// 保存总页参数到ViewState（减去ModPage()函数防止SQL语句执行时溢出查询范围，可以用存储过程分页算法来理解这句）
        ViewState["PageIndex"] = 0;                               // 保存一个为0的页面索引值到ViewState
        ViewState["JumpPages"] = PageCount;                       // 保存PageCount到ViewState，跳页时判断用户输入数是否超出页码范围

        this.Label1.Text = PageCount.ToString();   // 页面总数
        this.Label2.Text = RecCount.ToString();    // 记录条数
        if (RecCount <= 20)                        // 判断跳页文本框失效
            TextBox4.Enabled = false;              // 跳转文本框不能用
        TDataBind();                               // 调用数据绑定函数TDataBind()进行数据绑定运算
    }
    //计算余页
    public int OverPage()
    {
        int pages = 0;
        if (RecCount % PageSize != 0)   // 如果不能整除 说明有一页余页
            pages = 1;
        else                            // 否则余页为0
            pages = 0;
        return pages;
    }
    //计算余页，防止SQL语句执行时溢出查询范围
    public int ModPage()
    {
        int pages = 0;
        if (RecCount % PageSize == 0 && RecCount != 0)  // 如果没有余页并且 记录总数不为零
            pages = 1;
        else
            pages = 0;
        return pages;
    }
    // 计算总记录
    public int Calc()
    {
        try
        {
            int RecordCount = 0;
            RecordCount = pageDAL.GetTotalRow("vi_Book", selectStr);
            return RecordCount;
        }
        catch (Exception exp)
        {
            Response.Write("<script>alert('" + exp.Message + "');location.href='#'</script>");
            return -1;
        }
    }
    //对四个按钮（首页、上一页、下一页、尾页）返回的CommandName值进行操作
    private void Page_OnClick(object sender, CommandEventArgs e)
    {
        CurrentPage = (int)ViewState["PageIndex"];// 从ViewState中读取页码值保存到CurrentPage变量中进行参数运算
        Pages = (int)ViewState["PageCounts"];     // 从ViewState中读取 总页参数 运算

        string cmd = e.CommandName;
        switch (cmd)//筛选CommandName
        {
            case "next":
                CurrentPage++;
                break;
            case "prev":
                CurrentPage--;
                break;
            case "last":
                CurrentPage = Pages;
                break;
            default:
                CurrentPage = 0;
                break;
        }
        ViewState["PageIndex"] = CurrentPage;   // 将运算后的CurrentPage变量再次保存至ViewState
        TDataBind();                            // 调用数据绑定函数TDataBind()
    }
    // 数据绑定
    private void TDataBind()
    {
        CurrentPage = (int)ViewState["PageIndex"];// 从ViewState中读取页码值保存到CurrentPage变量中进行按钮失效运算
        Pages = (int)ViewState["PageCounts"];     // 从ViewState中读取 总页参数 进行按钮失效运算
        //判断四个按钮（首页、上一页、下一页、尾页）状态
        if (CurrentPage + 1 > 1)
        {
            Fistpage.Enabled = true;
            Prevpage.Enabled = true;
        }
        else
        {
            Fistpage.Enabled = false;
            Prevpage.Enabled = false;
        }
        if (CurrentPage == Pages)
        {
            Nextpage.Enabled = false;
            Lastpage.Enabled = false;
        }
        else
        {
            Nextpage.Enabled = true;
            Lastpage.Enabled = true;
        }
        //数据绑定到DataList控件
        try
        {
            DataSet ds = new DataSet();
            ds = pageDAL.Select("vi_Book", "", selectStr, PageSize, CurrentPage);
            if ((ds == null) ||
                (ds.Tables.Count == 0) ||
                (ds.Tables.Count == 1 && ds.Tables[0].Rows.Count == 0))
            { }
            else
            {
                ds.Tables[0].Columns.Add("sellprice");     // 添加新列（表示订单状态）
                ds.Tables[0].Columns.Add("sellCount");     // 添加新列（表示已卖出）
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    float Book_Priceflo;
                    float Book_Discountflo;
                    int Book_Countint;
                    int Book_ImportCountint;

                    Book_Priceflo = float.Parse(dr["Book_Priceflo"].ToString());
                    Book_Discountflo = float.Parse(dr["Book_Discountflo"].ToString());
                    Book_ImportCountint = Int32.Parse(dr["Book_ImportCountint"].ToString());
                    Book_Countint = Int32.Parse(dr["Book_Countint"].ToString());
                    dr["Book_Coverstr"] = "BackManage/UploadPicture/" + dr[8].ToString();     // 设置路径
                    dr["sellprice"] = Book_Priceflo * Book_Discountflo;                       // 现价
                    dr["sellCount"] = System.Math.Abs(Book_ImportCountint - Book_Countint);   // 已卖出
                }

                DataList1.DataSource = ds.Tables[0].DefaultView;
                DataList1.DataBind();

                Label3.Text = (CurrentPage + 1).ToString();    // 当前页数加加
                TextBox4.Text = (CurrentPage + 1).ToString();  // 跳转页面的页数加加
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('" + ex.Message.ToString() + "')</script>");
        }
    }

    #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
        //
        InitializeComponent();
        base.OnInit(e);
    }
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
        this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
        this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
        this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
        this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);

        this.TextBox4.TextChanged += new System.EventHandler(this.TextBox4_TextChanged);
        this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    //跳页代码
    private void TextBox4_TextChanged(object sender, System.EventArgs e)
    {
        try
        {
            JumpPage = (int)ViewState["JumpPages"];//从ViewState中读取可用页数值保存到JumpPage变量中
            //判断用户输入值是否超过可用页数范围值
            if (Int32.Parse(TextBox4.Text) > JumpPage && Int32.Parse(TextBox4.Text) <= 0)
            {

                Response.Write("<script>alert('页码范围越界！');location.href='#'</script>");
            }
            else
            {
                int InputPage = Int32.Parse(TextBox4.Text.ToString()) - 1;// 转换用户输入值保存在int型InputPage变量中
                ViewState["PageIndex"] = InputPage;                       // 写入InputPage值到ViewState["PageIndex"]中
                TDataBind();                                              // 调用数据绑定函数TDataBind()再次进行数据绑定运算
            }
        }                                                                 // 捕获由用户输入不正确数据类型时造成的异常
        catch (Exception exp)
        {
            Response.Write("<script>alert('" + exp.Message + "');location.href='#'</script>");
        }
    }
    private void GetWhereInfor(String where, String[] wherelist)
    {
        int firstindex = where.IndexOf("|", 0);
        wherelist[0] = where.Substring(0, firstindex);
        int secondindex = where.IndexOf("|", firstindex + 1);
        wherelist[1] = where.Substring(firstindex + 1, secondindex - (firstindex + 1));
        int thirdindex = where.IndexOf("|", secondindex + 1);
        wherelist[2] = where.Substring(secondindex + 1, thirdindex - (secondindex + 1));
        wherelist[3] = where.Substring(thirdindex + 1, where.Length - (thirdindex + 1));
    }
    protected void Unnamed3_Click(object sender, EventArgs e)
    {
        float minPrice = 0;
        float maxPrice = 0;

        if (this.TextBox2.Text.ToString() == null || this.TextBox2.Text.ToString() == "")
            minPrice = float.MinValue;
        else
            minPrice = float.Parse(this.TextBox2.Text.ToString());

        if (this.TextBox3.Text.ToString() == null || this.TextBox3.Text.ToString() == "")
            maxPrice = float.MaxValue;
        else
            maxPrice = float.Parse(this.TextBox3.Text.ToString());

        selectStr = "  Book_Namestr like '%" + this.TextBox1.Text.ToString() + "%' ";
        selectStr += "  and Book_Priceflo*Book_Discountflo BETWEEN " + minPrice.ToString() + " and " + maxPrice.ToString();
        selectStr += " and Book_Idint in (select Book_Idint from tbSecondBook_Seller) ";

        if (!object.Equals(Session["SelectStr"], null))  // 设置筛选条件
        {
            Session.Remove("SelectStr");
        }
        Session["SelectStr"] = selectStr;

        SetPageInfor();
    }
}
